package com.iteaj.iot.client;

import com.iteaj.iot.FrameworkException;
import com.iteaj.iot.IotThreadManager;
import com.iteaj.iot.LifeCycle;

import java.util.*;
import java.util.function.Consumer;

public class ClientComponentFactory implements LifeCycle {

    private static ClientComponentFactory instance = new ClientComponentFactory();
    private Map<Class<? extends ClientMessage>, ClientComponent> messageComponentMap = new HashMap(8);

    protected ClientComponentFactory() {  }

    public static ClientComponentFactory getInstance() {
        return ClientComponentFactory.instance;
    }

    public Collection<ClientComponent> getComponents() {
        return Collections.unmodifiableCollection(this.messageComponentMap.values());
    }

    public void forEach(Consumer<ClientComponent> action) {
        messageComponentMap.values().forEach(action);
    }

    public static ClientComponent getByClass(Class<? extends ClientMessage> messageClass) {
        return instance.messageComponentMap.get(messageClass);
    }

    public int size() {
        return this.messageComponentMap.size();
    }

    public ClientComponentFactory register(ClientComponent component) {
        Class aClass = component.getMessageClass();
        ClientComponent byClass = getByClass(aClass);
        if(byClass != null) {
            throw new FrameworkException("报文类型["+aClass.getSimpleName()+"的组件已经存在]");
        }

        this.messageComponentMap.put(aClass, component);
        return this;
    }

    /**
     * @param config {@link IotThreadManager}
     */
    @Override
    public void start(Object config) {
        getComponents().forEach(clientComponent -> {
            clientComponent.start(config);
        });
    }

    @Override
    public void close() {
        getComponents().forEach(clientComponent -> clientComponent.close());
    }
}
